package com.yn.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yn.common.enums.AuditStatusEnum;
import com.yn.common.exception.TransitException;
import com.yn.common.model.article.ArticleContent;
import com.yn.common.model.system.SystemAdmin;
import com.yn.common.model.user.User;
import com.yn.common.model.zy.CarBillDO;
import com.yn.common.model.zy.TCarFleetManageDO;
import com.yn.common.page.BasePage;
import com.yn.common.request.driver.CarBillQuery;
import com.yn.common.request.driver.CarBillRequest;
import com.yn.common.request.sc.PageParamRequest;
import com.yn.common.response.driver.CarBillDetailResponse;
import com.yn.common.response.driver.CarBillResponse;
import com.yn.common.response.driver.DriverBillList;
import com.yn.common.response.driver.DriverIncomeResponse;
import com.yn.common.vo.LoginUserVo;
import com.yn.service.dao.zy.CarBillMapper;
import com.yn.service.service.ICarBillService;
import com.yn.service.service.UserService;
import com.yn.service.zy.TCarFleetManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xuquanjun
 * @since 2025-07-01
 */
@Service
@Slf4j
public class CarBillServiceImpl extends ServiceImpl<CarBillMapper, CarBillDO> implements ICarBillService {
    @Autowired
    private TCarFleetManageService fleetManageService;
    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public void saveCarBill(CarBillRequest request) {
        //获得管理员信息 TODO
        CarBillDO carBillDO = new CarBillDO();
        BeanUtil.copyProperties(request, carBillDO);
        boolean save = save(carBillDO);
        if(!save){
            throw new TransitException("保存失败");
        }
        //将绑定的车队的账户收益金额增加
        TCarFleetManageDO fleetManageDO = fleetManageService.lambdaQuery()
                .eq(TCarFleetManageDO::getId, request.getCarFleetId())
                .eq(TCarFleetManageDO::getIsDelTag, false)
                .eq(TCarFleetManageDO::getAuditStatus, AuditStatusEnum.PASS.getCode()).one();
        if(fleetManageDO==null){
            throw new TransitException("车队还未通过审核，无法转账");
        }
        User byId = userService.getById(fleetManageDO.getAppUserId());
        BigDecimal income = byId.getIncome();
        if(income == null){
            income = BigDecimal.ZERO;
        }
        byId.setIncome(income.add(request.getTransferAmount()));

        boolean b = userService.updateById(byId);
        if(!b){
            throw new TransitException("保存失败");
        }
    }

    @Override
    public BasePage<CarBillResponse> listPage(CarBillQuery query, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<CarBillDO> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(query.getCarFleetId() != null, CarBillDO::getCarFleetId, query.getCarFleetId());
        lambdaQuery.eq(query.getTransferMethod() != null, CarBillDO::getTransferMethod, query.getTransferMethod());
        if(query.getKeywords() != null && !query.getKeywords().isEmpty()){
            lambdaQuery.and(i -> i.or().like(CarBillDO::getTransferMethod, query.getKeywords())
                    .or().like(CarBillDO::getMark, query.getKeywords()));
        }
        List<CarBillDO> carBillDOList = baseMapper.selectList(lambdaQuery);
        if(CollUtil.isEmpty(carBillDOList)){
            return BasePage.restPage(new ArrayList<>());
        }
        BasePage<CarBillDO> basePage = BasePage.restPage(carBillDOList);
        ArrayList<CarBillResponse> carBillResponses = new ArrayList<>(carBillDOList.size());
        for (CarBillDO carBillDO : carBillDOList) {
            CarBillResponse transform = CarBillResponse.transform(carBillDO);
            TCarFleetManageDO fleet = fleetManageService.getById(carBillDO.getCarFleetId());
            transform.setFleetName(fleet.getFleetName());
            transform.setFleetCuratorName(fleet.getFleetCuratorName());
            //TODO 操作人名称
            carBillResponses.add(transform);
        }
        BasePage<CarBillResponse> carBillResponseBasePage = BasePage.restPage(carBillResponses);
        BeanUtils.copyProperties(basePage, carBillResponseBasePage, "list");
        return carBillResponseBasePage;
    }

    @Override
    public CarBillDetailResponse getDetailById(Long id) {
        CarBillDO billDO = getById(id);
        if (billDO== null){
            throw new TransitException("未找到流水信息");
        }
        CarBillDetailResponse transform = CarBillDetailResponse.transform(billDO);
        TCarFleetManageDO fleet = fleetManageService.getById(billDO.getCarFleetId());
        transform.setFleetName(fleet.getFleetName());
        transform.setFleetCuratorName(fleet.getFleetCuratorName());
        transform.setFleetCuratorPhonenumber(fleet.getFleetCuratorPhonenumber());
        transform.setFleetAddress(fleet.getFleetAddress());
        //TODO 操作人名称
        return transform;
    }

    @Override
    public DriverIncomeResponse getFleetBill(Integer fleetId) {
        TCarFleetManageDO fleetDO = fleetManageService.getById(fleetId);
        if(fleetDO==null){
            throw new TransitException("未找到车队信息");
        }
        User user = userService.getById(fleetDO.getAppUserId());
        DriverIncomeResponse response = new DriverIncomeResponse();
        if(user.getIncome() == null){
            return null;
        }
        response.setIncome(user.getIncome().doubleValue());
        List<CarBillDO> list = this.lambdaQuery().eq(CarBillDO::getCarFleetId, fleetId).orderByDesc(CarBillDO::getTransferTime).list();
        if(list == null || list.isEmpty()){
            response.setBillLists(new ArrayList<>());
            return response;
        }
        ArrayList<DriverBillList> driverBillLists = new ArrayList<>(list.size());
        for (CarBillDO carBillDO : list) {
            DriverBillList driverBillList = new DriverBillList();
            BeanUtils.copyProperties(carBillDO, driverBillList);
            driverBillLists.add(driverBillList);
        }
        response.setBillLists(driverBillLists);
        return response;
    }
}
